<template>
  <view class="capsule-container">
    <scroll-view 
      class="capsule-scroll"
      scroll-x
      show-scrollbar="false"
      scroll-with-animation
      :scroll-left="scrollLeft"
    >
      <view 
        v-for="(item, index) in items"
        :key="index"
        class="capsule-item"
        :class="{ active: activeIndex === index }"
        @click="handleItemClick(index)"
        @longpress="handleLongPress(index)"
        :id="`capsule-item-${index}`"
      >
        {{ item }}
        <view v-if="showBadge && index === 0" class="capsule-badge">{{ pendingCount }}</view>
      </view>
    </scroll-view>

    <!-- 添加文件夹按钮 -->
    <view class="add-folder-btn" @click="emitAddFolder">
      <uni-icons type="plusempty" size="16" color="var(--primary-color)"></uni-icons>
    </view>

    <!-- 操作菜单 -->
    <uni-popup ref="actionMenu" type="bottom" safe-area @maskClick="closeActionMenu">
      <view class="action-menu">
        <view class="menu-title">文件夹操作</view>
        <view class="menu-item" @click="emitRename">
          <uni-icons type="compose" size="18" color="var(--text-secondary)"></uni-icons>
          <text>重命名</text>
        </view>
        <view 
          class="menu-item danger" 
          @click="emitDelete"
          v-if="selectedFolderIndex !== 0"
        >
          <uni-icons type="trash" size="18" color="var(--error-color)"></uni-icons>
          <text>删除</text>
        </view>
        <view class="menu-cancel" @click="closeActionMenu">
          <text>取消</text>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'

const props = defineProps({
  items: {
    type: Array,
    required: true,
    validator: (val) => val && val.length > 0
  },
  activeIndex: {
    type: Number,
    default: 0,
    validator: (val) => val >= 0
  },
  pendingCount: {
    type: Number,
    default: 0
  },
  showBadge: {
    type: Boolean,
    default: false
  },
  allowEdit: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['change', 'add-folder', 'rename-folder', 'delete-folder'])

const scrollLeft = ref(0)
const actionMenu = ref(null)
const selectedFolderIndex = ref(-1)
const selectedFolderName = ref('')

const handleItemClick = (index) => {
  if (index < 0 || index >= props.items.length) return
  emit('change', index)
  scrollToItem(index)
}

const handleLongPress = (index) => {
  if (!props.allowEdit || index < 0 || index >= props.items.length) return
  
  selectedFolderIndex.value = index
  selectedFolderName.value = props.items[index]
  actionMenu.value?.open()
}

const emitAddFolder = () => {
  emit('add-folder')
}

const emitRename = () => {
  if (selectedFolderIndex.value !== -1) {
    emit('rename-folder', {
      oldName: props.items[selectedFolderIndex.value],
      newName: ''
    })
  }
  closeActionMenu()
}

const emitDelete = () => {
  if (selectedFolderIndex.value !== -1) {
    emit('delete-folder', props.items[selectedFolderIndex.value])
  }
  closeActionMenu()
}

const closeActionMenu = () => {
  actionMenu.value?.close()
}

const scrollToItem = async (index) => {
  await nextTick()
  
  const query = uni.createSelectorQuery()
  query.select(`#capsule-item-${index}`).boundingClientRect()
  query.select('.capsule-scroll').boundingClientRect()
  query.exec((res) => {
    if (!res || !res[0] || !res[1]) {
      console.warn('Failed to get DOM rect')
      scrollLeft.value = 0
      return
    }

    const itemRect = res[0]
    const scrollRect = res[1]
    
    if (!itemRect || !scrollRect) {
      scrollLeft.value = 0
      return
    }

    scrollLeft.value = itemRect.left - (scrollRect.width / 2) + (itemRect.width / 2)
  })
}

watch(() => props.activeIndex, (newVal) => {
  if (newVal >= 0 && newVal < props.items.length) {
    scrollToItem(newVal)
  }
}, { immediate: true })
</script>

<style scoped>
.capsule-container {
  padding: 12px 16px;
  background-color: var(--background-color);
  display: flex;
  align-items: center;
  position: relative;
}

.capsule-scroll {
  white-space: nowrap;
  width: calc(100% - 40px);
  height: 100%;
}

.capsule-item {
  display: inline-flex;
  align-items: center;
  position: relative;
  padding: 8px 16px;
  margin-right: 8px;
  font-size: 14px;
  color: var(--primary-color);
  background-color: white;
  border: 1px solid var(--primary-color);
  border-radius: 16px;
  transition: all 0.3s;
}

.capsule-item:last-child {
  margin-right: 0;
}

.capsule-item.active {
  background-color: var(--primary-color);
  color: white;
}

.capsule-badge {
  position: absolute;
  top: -6px;
  right: -6px;
  min-width: 18px;
  height: 18px;
  padding: 0 4px;
  background-color: var(--secondary-color);
  color: white;
  border-radius: 9px;
  font-size: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-folder-btn {
  width: 32px;
  height: 32px;
  margin-left: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed var(--primary-color);
  border-radius: 16px;
  background-color: white;
}

.action-menu {
  background-color: white;
  border-radius: 12px 12px 0 0;
  padding: 12px 0;
}

.menu-title {
  padding: 8px 16px;
  font-size: 14px;
  color: var(--text-secondary);
  text-align: center;
  border-bottom: 1px solid var(--border-color);
}

.menu-item {
  padding: 16px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid var(--border-color);
}

.menu-item text {
  margin-left: 12px;
  font-size: 16px;
  color: var(--text-primary);
}

.menu-item.danger text {
  color: var(--error-color);
}

.menu-cancel {
  padding: 16px;
  text-align: center;
  font-size: 16px;
  color: var(--text-primary);
  margin-top: 8px;
}
</style>